package com.razorthink.shell.commands.essential;

import java.io.File;

import com.razorthink.shell.core.AbstractCommand;
import com.razorthink.shell.utils.CommandLogger;

public class CD extends AbstractCommand {

	public CD(String baseCommand, int params) {
		super(baseCommand, params);
	}

	@Override
	public void execute() {
		if (super.getCommandParser().getParamCount() < 1) {
			CommandLogger.logInfo("specify the directory path");
			return;
		}
		String dirPath = super.getCommandParser().getParams().get(0);
		if (dirPath.equals("..")) {
			if (super.getEnvVar("currentdir") != null) {
				String currentdir = (String) super.getEnvVar("currentdir")
						.getValue();
				String parent = new File(currentdir).getParent();
				if (parent != null) {
					changeDir(new File(currentdir).getParent());
				} else {
					CommandLogger.logInfo("Already at the root level");
				}
			} else {
				CommandLogger.logInfo("cd to a directory first");
			}
			return;
		}
		File dir = new File(dirPath);
		if (!dir.exists()) {
			CommandLogger.logInfo("Directory doesn't exist");
			return;
		}
		if (!dir.isDirectory()) {
			CommandLogger.logInfo("'" + dirPath + "' isn't a directory");
			return;
		}
		changeDir(dirPath);
	}

	public void changeDir(String dirPath) {
		super.setEnvVar("currentdir", dirPath);
		String newPrompt = "";
		if (super.getAppContext().getPrompt().contains("@")) {
			String[] arr = super.getAppContext().getPrompt().split("@");
			newPrompt = dirPath + "@" + arr[1];
		} else {
			newPrompt = dirPath + "@" + super.getAppContext().getPrompt();
		}
		super.getAppContext().setPrompt(newPrompt);
		return;
	}

	@Override
	public String getDescription() {
		return "change directory";
	}

	@Override
	public String getUsage() {
		return "cd [directory]";
	}

}
